﻿using System;
using System.Configuration;
using System.Linq;
using Sustainalytics.AwsS3.Client;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.Entities;
using Sustainalytics.Utils;
using Sustainalytics.Utils.Configuration;
using Sustainalytics.Entities.ConnectionStrings;
using Sustainalytics.DataLayer.ConnectionStrings;
using Sustainalytics.PregenerateScreeningReports.Service;
using Sustainalytics.Utils.Serilog;
using Sustainalytics.ScreeningTool.BL.Serilog;

namespace Sustainalytics.ScreeningTool.BL
{

    public interface IPregeneratedReportManager
    {


        PregeneratedReport GetReport(Guid accountId, Guid FilterId);

        void PersistFileS3(PregeneratedReport rpt);
    }



    public class PregeneratedReport:IEntity
    {
        public Guid Id { get; set; }

        public Guid AccountId { get; set; }

        public Guid FilterId { get; set; }

        public string ReportName { get; set; }

        public byte[] Content { get; set; }


        public override string ToString()
        {
            return string.Format("Id: {0}, AccountId: {1}, FilterId: {2}, ReportName: {3}", Id, AccountId, FilterId, ReportName);
        }
    }

    public class NullPregeneratedReport : PregeneratedReport
    {
        
    }



    public class PregeneratedReportManager:IPregeneratedReportManager
    {
        private readonly IS3Client _s3Client;
        private readonly IRepositoryCollection<PregeneratedReport> _repoPregenerated;
        private readonly IRepositoryCollection<Filter> _repoFilter; 
        private readonly string _s3Folder ;

        public PregeneratedReportManager()
        {
            var cnxClientPlatform = ConfigurationManager.ConnectionStrings["ClientPlatform"].ConnectionString;
            var connectionStringsManager = ConnectionStringsManager.GetInstance(ConnectionStringsRepository.GetInstance(cnxClientPlatform));
            var screeningDWcnx = connectionStringsManager.GetConnectionString(ConnectionStringType.ScreeningDW);

            _repoPregenerated = new RepositoryCollection<PregeneratedReport>(screeningDWcnx);
            _s3Client = new S3Client(new S3ClientSettings()
            {
                AccessKey = SettingsHelper.Read("accesKeyId", "AKIAJKGZZMOFAVOVLHJA"),
                SecretAccessKey = SettingsHelper.Read("awsSecretKey", "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"),
                ServiceEndPoint = SettingsHelper.Read("s3ServiceEndPoint", "https://s3-eu-west-1.amazonaws.com/")
            });
            var lastLetter = screeningDWcnx.Contains("ScreeningDW_A") ? "_A" : screeningDWcnx.Contains("ScreeningDW_B") ? "_B" : "";
            _s3Folder = SettingsHelper.Read("s3FolderPregen", "PregeneratedReports") + lastLetter;
            _repoFilter = new RepositoryCollection<Filter>(cnxClientPlatform);
        }


        public PregeneratedReportManager(IS3Client s3Client, IRepositoryCollection<PregeneratedReport> repoPregenerated, 
                                IRepositoryCollection<Filter> repoFilter, string s3Folder)
        {
            _s3Client = s3Client;
            _repoPregenerated = repoPregenerated;
            _repoFilter = repoFilter;
            _s3Folder = s3Folder;
        }

        public PregeneratedReport GetReport(Guid accountId, Guid FilterId)
        {
            try
            {
                var keyFound = string.Format("{0}_{1}", FilterId, accountId);
                var fileData = _repoPregenerated.ReadAllWhere(a => a.ReportName == keyFound).FirstOrDefault();
                if (fileData == null) { return new NullPregeneratedReport(); }
                fileData.Content =
                    _s3Client.DownloadFile(
                        bucket: SettingsHelper.Read("s3bucket", "dev-globalaccess-europe"),
                        key: string.Format("{0}/{1}.xlsx", _s3Folder, fileData.ReportName));
                fileData.ReportName = _repoFilter.ReadAllWhere(a => a.Id == FilterId).FirstOrDefault().Name;
                return fileData;
            }
            catch (Exception ex)
            {
                CommonEventSerilog.Log.Exception(ex);
                throw;
            }
        }

        public void PersistFileS3(PregeneratedReport rpt)
        {

            try
            {
                var content = rpt.Content;
                rpt.Content = null;
                var foundByFileName = _repoPregenerated.ReadAllWhere(a => a.ReportName == rpt.ReportName).FirstOrDefault();
                if (foundByFileName == null)
                {
                    _repoPregenerated.CreateOrUpdate(rpt);
                }
                var key = string.Format("{0}/{1}.xlsx", _s3Folder, rpt.ReportName);

                _s3Client.UploadFile(SettingsHelper.Read("s3bucket", "dev-globalaccess-europe"), key, content);

                CompanyScreeningSerilog.Log.ReportStatus(System.Diagnostics.Process.GetCurrentProcess().Id, String.Format("Upload to S3: {0}", key));
            }
            catch (Exception ex)
            {
                CommonEventSerilog.Log.Exception(ex);
                throw;
            }
        }

        public void CleanupS3()
        {
            var rpts = _repoPregenerated.ReadAll();
            if (!rpts.Any()) 
                return;

            foreach (var rpt in rpts)
            {
                _s3Client.DeleteFile(
                    bucket: SettingsHelper.Read("s3bucket", "dev-globalaccess-europe"),
                    key: string.Format("{0}/{1}.xlsx", _s3Folder, rpt.ReportName));
            }

            _repoPregenerated.Drop();
        }
    }
}
